package top.goldenyear.porpoise.framework.isolate.core.util;

import com.alibaba.ttl.TransmittableThreadLocal;

/**
 * @author airhead
 */
public class TenantContext {
  /** 当前租户编号 */
  private static final ThreadLocal<Long> TENANT_ID = new TransmittableThreadLocal<>();

  private static final ThreadLocal<Boolean> TENANT_IGNORE = new TransmittableThreadLocal<>();

  public static void enableTenant(Long tenantId) {
    TENANT_ID.set(tenantId);
    TENANT_IGNORE.set(Boolean.TRUE);
  }

  public static void ignoreTenant() {
    TENANT_ID.set(0L);
    TENANT_IGNORE.set(Boolean.FALSE);
  }

  public static Long getTenantId() {
    return TENANT_ID.get();
  }

  /**
   * 获得租户编号。如果不存在，则抛出 NullPointerException 异常
   *
   * @return 租户编号
   */
  public static Long getRequiredTenantId() {
    Long tenantId = getTenantId();
    if (tenantId == null) {
      throw new NullPointerException("TenantContextHolder 不存在租户编号！");
    }

    return tenantId;
  }

  public static Boolean getTenantIgnore() {
    return TENANT_IGNORE.get();
  }

  public static void clear() {
    TENANT_ID.remove();
    TENANT_IGNORE.remove();
  }
}
